<?php

namespace App\Admin\Forms;


use App\Models\SwtGood;
use App\Models\SwtGoodQuantity;
use App\Models\SwtMachine;
use App\Models\SwtReplenishment;
use App\Models\SwtReplenishmentGoods;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Form\NestedForm;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Illuminate\Support\Facades\DB;

class StartReplenishmentForm extends Form implements LazyRenderable
{
    use LazyWidget;
    public function handle(array $input)
    {
        $id = $this->payload['id'];

        Db::beginTransaction();
        $num = 0;
        $q_num = 0;
        try {
            SwtReplenishment::where('id',$id)->update(['replenishment_status'=>1,'leave_image'=>$input['leave_image']]);
            foreach ($input['goods'] as $value) {
                $goods_quantity = SwtGoodQuantity::where('goods_id',$value['id'])->first();
                if(empty($goods_quantity) || $quantity = ($goods_quantity->normal_quantity - $value['actual_quantity']) < 0){
                    $q_num++;
                }else{
                    $goods_quantity->update(['normal_quantity'=>$quantity]);
                }
                $res = SwtReplenishmentGoods::where(['replenishment_id'=>$id,'good_id'=>$value['id']]) -> update([
                    'actual_quantity' => $value['actual_quantity'],
                    'actual_price' => bcmul($value['actual_price'],100),
                ]);

                if(!$res) $num++;
            }

            if($num > 0) {
                throw new \Exception('商品出库修改异常，请重试');
            }

            if($q_num > 0) {
                throw new \Exception('商品库存不足，无法出库');
            }

            Db::commit();
            return $this->response()->success('出库成功')->refresh();
        } catch (\Exception $e) {
            Db::rollBack();
            return $this->response()->error($e->getMessage());
        }
    }


    public function form()
    {

        $this->text('replenishment_no', '补货单号')->disable();
        $this->display('replenishment_status', '状态')->disable();
        $this->text('machine_name', '设备')->disable();
        $this->display('operator_name', '补货员')->disable();

        $this -> table('goods','商品明细', function(NestedForm $table) {
            $table -> hidden('id');
            $table -> display('goods_name', '商品名');
            $table -> display('goods_quantity', '库存数量');

            $table -> display('replenishment_quantity', '预计出库数量');

            $table -> text('actual_price', '成本价');

            $table -> text('actual_quantity','实际出库数量')
                -> type('number')
                -> rules('required', [ 'required' => '数量不能为空'])
                -> attribute('min', 0)
                -> required();

        })->disableCreate()->disableDelete()->default($data['goods'] ?? [])-> setFieldClass(['table-text-center']);

        $this->image('leave_image','出库照片')->move('upload/replenishment');
    }

    public function default()
    {
        $id = $this->payload['id'];

        $replenishment_info = SwtReplenishment::where('id', $id)->first();
        $goods_info  = SwtReplenishmentGoods::with(['goods','goods_quantity']) -> where('replenishment_id', $id)->get()->toArray();

        $machine = SwtMachine::where('id',$replenishment_info->replenishment_machine_id)->first();
        $status_array = ['未出库','出库','补货完成'];

        $goods = [];

        foreach($goods_info as $key=>$value){
            $swt_good = SwtGood::where('id',$value['good_id'])->first();
            $goods[$key] = [
                'id' => $value['good_id'],
                'goods_name' => $value['goods']['goods_name'],
                'replenishment_quantity' => $value['replenishment_quantity'],
                'actual_price' => bcdiv($swt_good->cost_price,1000,2),
                'goods_quantity'=>$value['goods_quantity']['normal_quantity'] + $value['goods_quantity']['loss_quantity'],
            ];
        }




        $data = [
            'replenishment_no' => $replenishment_info->replenishment_no,
            'replenishment_status' => $status_array[$replenishment_info->replenishment_status],
            'machine_name' => !empty($machine->machine_name) ? $machine->machine_name : '',
            'operator_name' => $replenishment_info->operator_name,
            'goods' => $goods,
        ];
        return $data;
    }
}
